var mqtt=require('../../common/mqtt.min')

// 先去存储一下MQTT的连接参数
const mqtt_options = {
  clientId: 'k23b3hySH5l.wxdevice|securemode=2,signmethod=hmacsha256,timestamp=1739013612532|',
  username: 'wxdevice&k23b3hySH5l',
  password: '57fc328ba2ddef822c046a151bd558b8a05f47e22a4b9eb5bb0c7372345e7ad0'
}


App({
  eventBus: {
    listeners: {},
    on(event, callback) {
      if (!this.listeners[event]) {
        this.listeners[event] = [];
      }
      this.listeners[event].push(callback);
    },
    emit(event, data) {
      if (this.listeners[event]) {
        this.listeners[event].forEach(callback => callback(data));
      }
    },
    off(event) {
      if (this.listeners[event]) {
        delete this.listeners[event];
      }
    }
  },

  mqtt_connect() {
    console.log('开始连接阿里云物联网平台');
    // mqtt.connect 会返回一个跟阿里云物联网平台建立连接的一个对象(设备)
    // 我们这里说的是微信小程序连接阿里云物联网平台，但是实际上是微信小程序里面的一个变量去连接到了阿里云物联网平台
    this.globalData.mqtt_client = mqtt.connect('wxs://k23b3hySH5l.iot-as-mqtt.cn-shanghai.aliyuncs.com/mqtt', mqtt_options);

    // 监听，on函数
    const that = this;
    this.globalData.mqtt_client.on('connect', function (e) {
      console.log('连接成功');
      // 订阅主题
      that.globalData.mqtt_client.subscribe(
        '/k23b3hySH5l/wxdevice/user/get',
        function (err) {
          if (!err) {
            console.log('订阅主题成功');
          } else {
            console.error('订阅失败:', err);
          }}
      )// 补全 subscribe 回调闭合
    }),

    this.globalData.mqtt_client.on('message',function(topic,msg){
      const messageStr = msg.toString();
      console.log('Raw MQTT message:', messageStr);
      // 使用事件总线发送消息
      that.eventBus.emit('mqttMessage', messageStr);
    })
  },
  
  onLaunch() {
    this.mqtt_connect()
  },

  globalData: {
    mqtt_client: null
  }
})
